﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using SEAM.Exception.Formatter;
using System.Diagnostics;

namespace SEAM.Exception.Publisher
{
    public class LogFilePublisher : ExceptionPublisherBase
    {
        private string _logFile = null;
        public string LogFile
        {
            get { return _logFile; }
            set { _logFile = value; }
        }

        public LogFilePublisher(XmlNode node) 
            : base(node) 
        {
            LogFile = GetAttributeValue(node, "logFile", true);

            try
            {
                StreamWriter writer = new StreamWriter(LogFile, true);
                writer.Close();
            }
            catch (System.Exception ex)
            {
                throw new ArgumentException("Unable to write to " + LogFile, "logFile", ex);
            }
        }

        public override bool PublishException(System.Exception ex, IDictionary<string, object> additionalInfo)
        {
            try
            {
                StreamWriter writer = new StreamWriter(LogFile, true);
                writer.Write(GetFormattedMessage(ex, Format, additionalInfo));
                writer.Close();
            }
            catch (System.Exception ex2)
            {
                Trace.TraceWarning(ex2.Message + Environment.NewLine + ex2.StackTrace);
                return false;
            }
            return true;
        }
    }
}
